package serve;

import Common.Message;
import Common.MessageType;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class FileClientServe {
    public void sendFile(String src,String sendId,String getterId,String dest){
        //1.组装信息对象
        Message message=new Message();
        message.setSrc(src);
        message.setDest(dest);
        message.setSender(sendId);
        message.setReceiver(getterId);
        message.setMsgType(MessageType.MESSAGE_FILE_SEND
        );
        FileInputStream fis=null;
        try {
            if ((int) new File(src).length()>Integer.MAX_VALUE){
                System.out.println("文件太长了");
                return;
            }

            byte[] fileBytes=new byte[(int) new File(src).length()];
            fis=new FileInputStream(src);
            fis.read(fileBytes);
            message.setFileBytes(fileBytes);
            new ObjectOutputStream(ManageClientConnectServeThread.getClientConnectServiceThread(sendId).getSocket().getOutputStream()).writeObject(message.getFileBytes());
        }catch (Exception e){
            e.getMessage();
        }finally {
            try {
                fis.close();
            }catch (Exception e){
                e.getMessage();
            }
        }
        System.out.println(sendId + " 给 " + getterId + " 发送文件 " + src + " 到对方的电脑目录 " +dest);
        // 获得线程
        ClientConnectServiceThread thread = ManageClientConnectServeThread.getClientConnectServiceThread(sendId);
        // 从线程中拿到 socket
        Socket socket = thread.getSocket();
        // 拿到 流对象
        try {
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            // 写入
            oos.writeObject(message);

        }catch (Exception e){
            System.out.println(e.getMessage());
        }

    }
}

